﻿package  com.hadron {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	/**
	 * ...
	 * @author Labielos & Haderos
	 */
	public class ImageLoader
	{
		public static const IMAGES_LOADED_EVENT:String = "ImageLoadedRequest";
		
		private var _target:EventDispatcher;
		
		private var urlRequest:URLRequest = new URLRequest();
		private var loader:Loader = new Loader();
		private var urlLoader:URLLoader = new URLLoader();
		private var bmpArray:Array = [];
		
		private var fileNames:Array = [];
		private var imgLoadedIndex:int;
		
		private var bmp:Bitmap;
		private var bmpData:BitmapData;
		
		public function ImageLoader(target:EventDispatcher) 
		{
			_target = target;
			urlRequest.method = URLRequestMethod.POST;
		}
		
		public function get images():Array
		{
			if (bmpArray.length == 0)
			{
				trace("nic tu qwa nie ma!");
				return null;
			}
			return bmpArray;
		}
		
		public function loadImages(filesListPath:String):void
		{
			urlRequest.url = filesListPath;
			urlLoader.addEventListener(Event.COMPLETE, filesLoaderHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{trace('error byl!');});
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			urlLoader.load(urlRequest);
		}
		
		private function filesLoaderHandler(e:Event):void
		{
			urlLoader.removeEventListener(Event.COMPLETE, filesLoaderHandler);
			
			while (fileNames.length > 0)
			{
				fileNames.pop();
			}
			
			var fileContent:String = urlLoader.data as String;
			fileNames = fileContent.split(';');
			
			while (bmpArray.length > 0)
			{
				bmpArray.pop();
			}
			
			imgLoadedIndex = 0;
			loadImage(fileNames[0]);
		}
		
		private function loadImage(srcPath:String):void
		{
			if (imgLoadedIndex == 0)
			{
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoadedHandler);
			}
			if (imgLoadedIndex == fileNames.length)
			{
				loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, imageLoadedHandler);
				++imgLoadedIndex;
				_target.dispatchEvent(new Event(IMAGES_LOADED_EVENT));
				return;
			}
			urlRequest.url = srcPath;			
			loader.load(urlRequest);
		}
		
		private function imageLoadedHandler(e:Event):void
		{
			bmpData = new BitmapData(loader.content.width, loader.content.height, false, 0);
			bmpData.draw(loader.content);
			bmp = new Bitmap(bmpData, "auto", true);
			bmpArray.push(bmp);	

			loadImage(fileNames[ ++imgLoadedIndex ]);
		}
		
		public function get countAll():int
		{
			return fileNames.length;
		}
		
		public function get countLoaded():int
		{
			return imgLoadedIndex;
		}
	}
	
}